package com.baozhun.mall.common.widget.customview.colorselect

import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import android.widget.RelativeLayout
import com.baozhun.mall.common.R
import com.baozhun.mall.common.model.bean.ColorListItem
import java.lang.Exception

/**
 * @Title：
 * @Description：
 * @Author：xing.luo
 * @Since：2022/11/13
 * @Version：1.0.0
 */
class ColorSelectHorizontalScrollView: RelativeLayout {
    var current: Int = 0
    var colors = listOf<ColorListItem>()
    var mRootView: View? = null
    var containerView: LinearLayout? = null
    var leftView: View? = null
    var rightView: View? = null
    var listener: OnClickListener? = null

    constructor(context: Context?) : super(context!!) {
        initView(context)
    }
    constructor(context: Context?, attrs: AttributeSet?) : super(context!!, attrs) {
        initView(context)
    }
    constructor(context: Context?, attrs: AttributeSet?, defStyle: Int) : super(
        context!!,
        attrs,
        defStyle
    ) {
        initView(context)
    }

    fun initView(context: Context) {
        mRootView = LayoutInflater.from(context).inflate(R.layout.widget_color_select_horizontal_scrollview, this)
        containerView = mRootView?.findViewById(R.id.item_colors_linearlayout) as LinearLayout
        rightView = mRootView?.findViewById(R.id.item_color_right_iv)
        leftView = mRootView?.findViewById(R.id.item_color_left_iv)
    }

    fun initData(colors: List<ColorListItem>, listener: OnClickListener) {
        containerView?.removeAllViews()
        this.colors = colors
        this.listener = listener
        if (colors.size <= 5) {
            rightView?.visibility = View.GONE
            leftView?.visibility = View.GONE
        }
        var index: Int = 0
        for(color in colors) {
            val button = ColorButton(context)
            button.tag = index
            index++
            try {
                button.setColor(color.color_img , Color.parseColor(color.color))
            } catch (tr: Exception) {
                button.setColor(Color.parseColor("#F0F0F0"))
            }
            if (colors.size > 1) {
                button.setOnClickListener(OnClickListener {
                    it.apply {
                        isSelected = true
                        containerView?.getChildAt(current)?.isSelected = false
                        val selfIndex = tag as Int
                        current = selfIndex
                        listener.onClick(button)
                    }
                })
            }
            containerView?.addView(button)
        }

        containerView?.getChildAt(current)?.isSelected = true
    }
}